import ReactDOM from "react-dom/client";
import { createPortal } from "react-dom";
import React, { useEffect, useRef } from "react";

// Modal 组件
const Modal = ({ visible, content, onClose, initialPosition }) => {
  const modalRef = useRef(null);

  useEffect(() => {
    if (modalRef.current) {
      modalRef.current.style.transform = `translate(${initialPosition.x}px, ${initialPosition.y}px) scale(0)`; // 初始位置和缩放为0
      requestAnimationFrame(() => {
        modalRef.current.style.transform = "translate(-50%, -50%) scale(1)"; // 向中间移动并放大
      });
    }
  }, [initialPosition]);

  if (!visible) return null;

  return createPortal(
    <div style={styles.overlay} onClick={onClose}>
      <divs
        ref={modalRef}
        style={styles.modal}
        onClick={(e) => e.stopPropagation()}
      >
        {content}
        <button style={styles.closeBtn} onClick={onClose}>
          关闭
        </button>
      </divs>
    </div>,
    document.body
  );
};

// 创建 Modal 的函数
const createModal = (content, event) => {
  const container = document.createElement("div");
  document.body.appendChild(container);

  const root = ReactDOM.createRoot(container); // 创建根

  const closeModal = () => {
    root.unmount(); // 卸载组件
    document.body.removeChild(container); // 移除 DOM
  };

  const { clientX, clientY } = event;

  const initialPosition = {
    x: clientX,
    y: clientY,
  };

  root.render(
    <Modal
      visible={true}
      content={content}
      onClose={closeModal}
      initialPosition={initialPosition}
    />
  );

  return { close: closeModal };
};

// 样式
const styles = {
  overlay: {
    position: "fixed",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  },
  modal: {
    backgroundColor: "white",
    padding: "20px",
    borderRadius: "8px",
    boxShadow: "0 2px 10px rgba(0, 0, 0, 0.3)",
    maxWidth: "400px",
    width: "100%",
    position: "relative",
    zIndex: 1000,
    transition: "transform 0.5s ease", // 添加过渡效果
    transform: "translate(-50%, -50%) scale(1)", // 确保缩放为1
  },
  closeBtn: {
    marginTop: "10px",
    padding: "5px 10px",
    cursor: "pointer",
  },
};

export { createModal, styles };
